package com.zzb.service.impl;

import com.github.pagehelper.PageHelper;
import com.zzb.DTO.NewsDTO;
import com.zzb.DTO.ResultDTO;
import com.zzb.VO.NewsVO;
import com.zzb.dao.NewsDao;
import com.zzb.entity.NewsEntity;
import com.zzb.service.NewsService;
import com.zzb.util.Tool;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
    NewsEntity newsEntity = new NewsEntity();
    @Resource
    NewsDao newsDao;
    @Override
    public ResultDTO add(NewsVO newsVO) {
        //数据复制
        BeanUtils.copyProperties(newsVO, newsEntity);
        if(newsDao.add(newsEntity)==1){
            return ResultDTO.getResult("success",1);
        }else {
            return ResultDTO.getResult("error",0);
        }
    }

    @Override
    public ResultDTO delete(NewsVO newsVO) {
        //数据复制
        BeanUtils.copyProperties(newsVO, newsEntity);
        //判断新闻是否存在
        if (newsDao.findById(newsEntity) != null) {
            //存在
            return ResultDTO.getResult("success", newsDao.delete(newsEntity));
        } else {//不存在
            return ResultDTO.getResult("error", 0);
        }
    }

    @Override
    public ResultDTO findById(NewsVO newsVO) {
        BeanUtils.copyProperties(newsVO, newsEntity);
        newsEntity = newsDao.findById(newsEntity);
        if (newsEntity != null) {
            NewsDTO newsDTO = new NewsDTO();
            BeanUtils.copyProperties(newsEntity, newsDTO);
            return ResultDTO.getResult("success", newsDTO);
        } else {
            return ResultDTO.getResult("error", 0);
        }
    }

    @Override
    public ResultDTO findAll(NewsVO newsVO) {
        BeanUtils.copyProperties(newsVO, newsEntity);
        int count = newsDao.count(newsEntity);
        PageHelper.startPage(newsEntity.getPage(),newsEntity.getLimit());
        List<NewsEntity> list = newsDao.findAll(newsEntity);
        //集合复制
        List<NewsDTO> newsDTOList = Tool.copy(list, NewsDTO.class);
        return ResultDTO.getResult(count, newsDTOList);
    }

    @Override
    public ResultDTO update(NewsVO newsVO) {
        BeanUtils.copyProperties(newsVO, newsEntity);
        return ResultDTO.getResult(newsDao.update(newsEntity));
    }
}
